<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属单位" prop="customerId">
        <el-select
          v-model="queryParams.customerId"
          placeholder="所属单位"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="customer in customerList"
            :key="customer.customerName"
            :value="customer.customerId"
            :label="customer.customerName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="供应单位" prop="enterpriseId">
        <el-select
          v-model="queryParams.enterpriseId"
          placeholder="供应单位"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="customer in customerList_r"
            :key="customer.customerName"
            :value="customer.customerId"
            :label="customer.customerName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="结算时间" prop="settleTime">
        <el-date-picker clearable
          v-model="queryParams.settleTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择结算开始时间">
        </el-date-picker>
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择结算结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="车头信息" prop="carInfo">
        <el-input
          v-model="queryParams.carInfo"
          placeholder="请输入车头信息"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sale:sale:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['sale:sale:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['sale:sale:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sale:sale:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="saleList" @selection-change="handleSelectionChange" border>
<!--      <el-table-column :selectable="selectable" type="selection" width="55" align="center" />-->
      <el-table-column label="销售记录ID" align="center" prop="saleRecordId" v-if="false" />
      <el-table-column label="所属单位ID" align="center" prop="customerId" v-if="false" />
      <el-table-column label="充气编号" align="center" prop="fullfillNum" />
      <el-table-column label="所属单位" align="center" prop="customerName" width="120" />
      <el-table-column label="充气量(m³)" align="center" prop="amount" width="120" />
      <el-table-column label="进气价格（元）" align="center" prop="salePrice" width="120" />
      <!--      <el-table-column label="实际卖气量(m³)" align="center" prop="factAmount" width="120" />-->
      <el-table-column label="合计金额（元）" align="center" prop="saleAmount" width="120" />
      <el-table-column label="结算时间" align="center" prop="settleTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.settleTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="车头号" align="center" prop="carInfo" width="100" />
      <el-table-column label="车身号" align="center" prop="carNum" width="100" />
      <el-table-column label="经销商名称" align="center" prop="enterpriseName" width="120" />
      <!--<el-table-column label="往返公里数" align="center" prop="mileage" width="100" />
      <el-table-column label="车头耗气量" align="center" prop="carHeadConsume" width="100" />
      <el-table-column label="车头耗气量单价" align="center" prop="consumeSinglePrice" width="120" />
      <el-table-column label="耗气金额" align="center" prop="consumeAmount" />
      <el-table-column label="高速公路费" align="center" prop="highwayAmount" width="100" />
      <el-table-column label="司机工资" align="center" prop="driverSalary" />
      <el-table-column label="押运员工资" align="center" prop="supercargoSalary" width="100" />
      <el-table-column label="其他费用" align="center" prop="otherAmount" />
      <el-table-column label="费用总额" align="center" prop="totalAmount" />
      <el-table-column label="亏涨量(m³)" align="center" prop="lossIncrease" width="100" />

      <el-table-column label="出气价格" align="center" prop="outPrice" />
      <el-table-column label="出气量(m³)" align="center" prop="outAmount" width="100" />
      <el-table-column label="供应单位ID" align="center" prop="enterpriseId" v-if="false" />


      <el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <span v-if="scope.row.operation">
          </span>
          <span v-else>
<!--            <el-button-->
<!--              size="mini"-->
<!--              type="text"-->
<!--              icon="el-icon-edit"-->
<!--              @click="handleUpdate(scope.row)"-->
<!--              v-hasPermi="['sale:sale:edit']"-->
<!--            >修改</el-button>-->
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['sale:sale:remove']"
            >删除</el-button>
          </span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改销售记录
对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="所属单位" prop="customerId">
          <el-select v-model="form.customerId" placeholder="请选择单位" @change="selectCustomer">
            <el-option
              v-for="customer in customerList"
              :key="customer.customerName"
              :value="customer.customerId"
              :label="customer.customerName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应单位" prop="customerId">
          <el-select v-model="form.enterpriseId" placeholder="请选择单位" @change="selectCustomerR">
            <el-option
              v-for="customer in customerList_r"
              :key="customer.customerName"
              :value="customer.customerId"
              :label="customer.customerName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="卖气价格" prop="salePrice">
          <el-input v-model="form.salePrice" placeholder="请输入卖气价格">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">元</i>
          </el-input>
        </el-form-item>
        <el-form-item label="实际卖气量(m³)" prop="factAmount">
          <el-input v-model="form.factAmount" placeholder="请输入实际卖气量(m³)">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">m³</i>
          </el-input>
        </el-form-item>
        <el-form-item label="卖气数量(m³)" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入卖气数量(m³)">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">m³</i>
          </el-input>
        </el-form-item>
        <el-form-item label="卖气金额" prop="saleAmount">
          <el-input v-model="form.saleAmount" placeholder="请输入卖气金额">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">元</i>
          </el-input>
        </el-form-item>
        <el-form-item label="结算时间" prop="settleTime">
          <el-date-picker clearable
            v-model="form.settleTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择结算时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="销售对象" prop="carInfo">
          <el-input v-model="form.carInfo" placeholder="请输入销售对象" />
        </el-form-item>
        <el-form-item label="车次" prop="carNum">
          <el-input v-model="form.carNum" placeholder="请输入车次" />
        </el-form-item>
       <!-- <el-form-item label="往返公里数" prop="mileage">
          <el-input v-model="form.mileage" placeholder="请输入往返公里数">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">km</i>
          </el-input>
        </el-form-item>
        <el-form-item label="车头耗气量" prop="carHeadConsume">
          <el-input v-model="form.carHeadConsume" placeholder="请输入车头耗气量">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">m³</i>
          </el-input>
        </el-form-item>
        <el-form-item label="车头耗气量单价" prop="consumeSinglePrice">
          <el-input v-model="form.consumeSinglePrice" placeholder="请输入车头耗气量单价">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">元</i>
          </el-input>
        </el-form-item>
        <el-form-item label="耗气金额" prop="consumeAmount">
          <el-input v-model="form.consumeAmount" placeholder="请输入耗气金额">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">元</i>
          </el-input>
        </el-form-item>
        <el-form-item label="高速公路费" prop="highwayAmount">
          <el-input v-model="form.highwayAmount" placeholder="请输入高速公路费">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">元</i>
          </el-input>
        </el-form-item>
        <el-form-item label="司机工资" prop="driverSalary">
          <el-input v-model="form.driverSalary" placeholder="请输入司机工资">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">元</i>
          </el-input>
        </el-form-item>
        <el-form-item label="押运员工资" prop="supercargoSalary">
          <el-input v-model="form.supercargoSalary" placeholder="请输入押运员工资">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">元</i>
          </el-input>
        </el-form-item>
        <el-form-item label="其他费用" prop="otherAmount">
          <el-input v-model="form.otherAmount" placeholder="请输入其他费用">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">元</i>
          </el-input>
        </el-form-item>
        <el-form-item label="费用总额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入费用总额">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">元</i>
          </el-input>
        </el-form-item>
        <el-form-item label="亏涨量(m³)" prop="lossIncrease">
          <el-input v-model="form.lossIncrease" placeholder="请输入亏涨量(m³)">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">m³</i>
          </el-input>
        </el-form-item>
        <el-form-item label="出气价格" prop="outPrice">
          <el-input v-model="form.outPrice" placeholder="请输入出气价格">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">元</i>
          </el-input>
        </el-form-item>
        <el-form-item label="出气量(m³)" prop="outAmount">
          <el-input v-model="form.outAmount" placeholder="请输入出气量(m³)">
            <i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 30px;">m³</i>
          </el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSale, listAll, getSale, delSale, addSale, updateSale } from "@/api/sale/sale";
import { listCustomer } from "@/api/base/customer";
import * as math from 'mathjs'

export default {
  name: "Sale",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      saleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: null,
        settleTime: null,
        carInfo: null,
        carNum: null,
      },
      // 表单参数
      form: {},
      customerList: [],
      customerList_r: [],
      // 表单校验
      rules: {
        customerId: [
          { required: true, message: "所属单位不能为空", trigger: "blur" }
        ],
        purchaseUnitId: [
          { required: true, message: "采购单位不能为空", trigger: "blur" }
        ],
        amount: [
          { required: true, message: "卖气数量不能为空", trigger: "blur" },
          { pattern: /^\d+[.]?\d{0,2}$/, message: '必须为正整数或小数保留两位小数', trigger: "blur" }
        ],
        factAmount: [
          { required: true, message: "实际卖气数量不能为空", trigger: "blur" },
          { pattern: /^\d+[.]?\d{0,2}$/, message: '必须为正整数或小数保留两位小数', trigger: "blur" }
        ],
        salePrice: [
          { required: true, message: "卖气价格不能为空", trigger: "blur" },
          { pattern: /^\d+[.]?\d{0,2}$/, message: '必须为正整数或小数保留两位小数', trigger: "blur" }
        ],
        outPrice: [
          { required: true, message: "出气价格不能为空", trigger: "blur" },
          { pattern: /^\d+[.]?\d{0,2}$/, message: '必须为正整数或小数保留两位小数', trigger: "blur" }
        ],
        outAmount: [
          { required: true, message: "出气量不能为空", trigger: "blur" },
          { pattern: /^\d+[.]?\d{0,2}$/, message: '必须为正整数或小数保留两位小数', trigger: "blur" }
        ],
        carInfo: [
          { required: true, message: "销售对象不能为空", trigger: "blur" }
        ],
        totalAmount: [
          { required: true, message: "费用总额不能为空", trigger: "blur" },
          { pattern: /^-*\d+[.]?\d{0,2}$/, message: '必须为整数或小数保留两位', trigger: "blur" }
        ],
        lossIncrease: [
          { required: true, message: "亏涨量不能为空", trigger: "blur" },
          { pattern: /^-*\d+[.]?\d{0,2}$/, message: '必须为整数或小数保留两位', trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询销售记录
列表 */
    getList() {
      this.loading = true;
      listSale(this.queryParams).then(response => {
        this.saleList = response.rows;
        this.total = response.total;
        this.loading = false;
        if(this.queryParams.pageSize > response.rows.length || this.queryParams.pageNum * this.queryParams.pageSize == response.total) {
          var total = {}
          const query = { ...this.queryParams }
          Reflect.deleteProperty(query, 'pageNum')
          Reflect.deleteProperty(query, 'pageSize')
          listAll(query).then(response => {
            var factAmount = math.bignumber(0), amount = math.bignumber(0), outAmount = math.bignumber(0)
            response.forEach(function(item, index) {
              const factAmountValue = Number(item.factAmount);
              if (!isNaN(factAmountValue)) {
                factAmount = math.add(factAmount, factAmountValue)
              }
              const amountValue = Number(item.amount);
              if (!isNaN(amountValue)) {
                amount = math.add(amount, amountValue)
              }
              const outAmountValue = Number(item.outAmount);
              if (!isNaN(outAmountValue)) {
                outAmount = math.add(outAmount, outAmountValue)
              }
            })
            total.factAmount = math.number(factAmount)
            total.amount = math.number(amount)
            total.outAmount = math.number(outAmount)
            total.operation = true
            total.customerName = '总计'
            this.saleList.push(total)
          });
        }
      });
      var customerParam = { customerType: 1 }
      listCustomer(customerParam).then(response => {
        this.customerList = response.rows;
      });
      customerParam.customerType = 2
      listCustomer(customerParam).then(response => {
        this.customerList_r = response.rows;
      });
    },
    selectable(row, index) {
      if(row.operation) {
        return false
      } else {
        return true
      }
    },
    selectCustomer(value) {
      var obj = {}
      obj = this.customerList.find(function(item){
        return item.customerId === value
      });
      this.form.customerName = obj.customerName
    },
    selectCustomerR(value) {
      var obj = {}
      obj = this.customerList_r.find(function(item){
        return item.customerId === value
      });
      this.form.enterpriseName = obj.customerName
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        saleRecordId: null,
        customerId: null,
        customerName: null,
        salePrice: null,
        factAmount: null,
        amount: null,
        saleAmount: null,
        settleStatus: "0",
        settleTime: null,
        carInfo: null,
        carNum: null,
        mileage: null,
        carHeadConsume: null,
        consumeSinglePrice: null,
        consumeAmount: null,
        highwayAmount: null,
        driverSalary: null,
        supercargoSalary: null,
        otherAmount: null,
        totalAmount: null,
        lossIncrease: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.saleRecordId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const saleRecordId = row.saleRecordId || this.ids
      getSale(saleRecordId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.saleRecordId != null) {
            updateSale(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSale(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const saleRecordIds = row.saleRecordId || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + saleRecordIds + '"的数据项？').then(function() {
        return delSale(saleRecordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sale/sale/export', {
        ...this.queryParams
      }, `sale_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
